package com.naire.modul.contract.dao.impl;

import java.util.ArrayList;
import java.util.List;

import net.common.dao.GeneralDaoImpl;
import net.common.service.PageBean;
import net.common.util.BeanUtils;

import com.naire.modul.contract.dao.ContractDao;
import com.naire.modul.contract.pojo.Contract;
import com.naire.modul.contract.vo.ContractVo;
import com.naire.modul.customer.pojo.Customer;

public class ContractDaoImpl extends GeneralDaoImpl implements ContractDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<ContractVo> search(PageBean pageBean) throws Exception {
		StringBuilder hql = new StringBuilder("from Contract where flag=0");
		List<ContractVo> d = new ArrayList<ContractVo>();
		List<Contract> l = hibernateHandler.query(hql, pageBean);
		for(Contract bean : l) {
			ContractVo dv = new ContractVo();
			BeanUtils.copyProperties(bean, dv);
			dv.setCust_name(bean.getCustomer().getCust_name());
			d.add(dv);
		}
		return d;
	}

	@Override
	public void insert(ContractVo bean) throws Exception {
		Contract pojo = new Contract();
		BeanUtils.copyProperties(bean, pojo);
		if(bean.getCust_id() != null) {
			Customer c = (Customer) hibernateHandler.find(Customer.class, bean.getCust_id());
			pojo.setCustomer(c);
		}
		hibernateHandler.insert(pojo);
	}

	@Override
	public void update(ContractVo bean) throws Exception {
		Contract pojo = (Contract)hibernateHandler.find(Contract.class, bean.getContract_id());
		BeanUtils.copyProperties(bean, pojo);
		if(bean.getCust_id() != null) {
			Customer c = (Customer) hibernateHandler.find(Customer.class, bean.getCust_id());
			pojo.setCustomer(c);
		}
		hibernateHandler.update(pojo);
	}

	@Override
	public void updateFlag(ContractVo bean) throws Exception {
		update(bean);
	}

	@Override
	public ContractVo find(Integer id) throws Exception {
		Contract pojo = (Contract)hibernateHandler.find(Contract.class, id);
		ContractVo bean = new ContractVo();
		BeanUtils.copyProperties(pojo, bean);
		Customer c = pojo.getCustomer();
		bean.setCust_id(c.getCust_id());
		bean.setCust_name(c.getCust_name());
		return bean;
	}
}
